<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>MessageChannel - port1</title>
	</head>

	<body>
		<p id="pRef"></p>
		<input type="button" value="点击发送给port1" id="btnRef" />
		<script>
			const pRef = document.querySelector('#pRef')
			const btnRef = document.querySelector('#btnRef')
			let port2
			// 监听 message 事件，设置 port2
			window.addEventListener('message', (e) => {
				port2 = e.ports[0]
				// 设置 port2 onmessage 事件
				port2.onmessage = handleMessage
			})
			btnRef.addEventListener('click', () => {
				// port2 给 port1 发送消息
				port2.postMessage(Math.random())
			})

			function handleMessage(e) {
				pRef.textContent = 'port2-count：' + e.data
			}
		</script>
	</body>
</html>
